<?php

namespace app\api\model\wanlshop;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Activity extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'wanlshop_activity';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'starttime_text',
        'endtime_text'
    ];






    public function getStarttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['starttime']) ? $data['starttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['endtime']) ? $data['endtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStarttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function goods(){
        return $this->hasMany('ActivityGoodsSku', 'activity_id', 'id');
    }


    // 检测商品是否参与秒杀活动
    public function checkActivity($goods_id){
        if($goods_id){
            $where = [
                ['exp', Db::raw("FIND_IN_SET($goods_id,goods_ids)")],
                'type' => 'seckill',
                'state' => 'doing',
                'starttime' =>['<',time()],
                'endtime' =>['>',time()],
            ];

            $activity = $this->where($where)->find();

            return $activity;
        }else{
            return false;
        }

    }

    // 商品关联的组合套餐
    public function package($goods_id){
        $currency_rate = model('app\api\model\wanlshop\Pay')->getCurrencyRate('',0);
        $activity = $this->where([
            ['exp', Db::raw("FIND_IN_SET($goods_id,goods_ids)")],
            'type' => 'package'
        ])->field('id,title,goods_ids,type,rules')->select();
        if($activity){
            foreach ($activity as $item){
                $item['price'] = json_decode($item['rules'],true)['price'];
                $item['rmb_price'] = bcmul(json_decode($item['rules'],true)['price'], $currency_rate, 2);;
                $goods = model('app\api\model\wanlshop\ActivityGoodsSku')
                    ->with(['sku','goodssku'=>function($query){
                        $query->where(['state' => '0']);
                    },'goods'])
                    ->where([
                        'activity_id' => $item['id']
                    ])
                    ->select();

                $item['goods'] = $goods;
            }
            return $activity;
        }
        return [];
    }

    //检测组合套餐
    public function checkPackage($order,$action = 'getOrderGoodsList'){
        $package = false;
        $count = count($order['products']);
        $shop_id = $order['shop_id'];
        if($action == 'getOrderGoodsList'){
            $goods_ids = array_column($order['products'],'id');
            $products = collection(array_column($order['products'],null,'id'))->toArray();
        }elseif($action == 'addOrder'){
            $goods_ids = array_column($order['products'],'goods_id');
            $products = array_column($order['products'],null,'goods_id');
        }else{
            return $package;
        }

        $where = [];
        foreach ($goods_ids as $goods_id){
            $where[] = ['exp', Db::raw("FIND_IN_SET($goods_id,goods_ids)")];
        }
        $activitys = $this->with(['goods'])->where($where)
            ->where('type','package')
            ->where('shop_id',$shop_id)
            ->field('id,title,goods_ids,type,rules')
            ->select();

        foreach ($activitys as $activity){
            $goods_ids_count = count(explode(',',$activity['goods_ids']));
            if($count != $goods_ids_count){
                continue;
            }
            foreach ($activity['goods'] as $goods){
                if($action == 'getOrderGoodsList'){
                    $sku_id = $products[$goods['goods_id']]['sku']['id'];

                }elseif($action == 'addOrder'){
                    $sku_id = $products[$goods['goods_id']]['sku_id'];
                }else{
                    $sku_id = 0;
                }
                $number = $products[$goods['goods_id']]['number'];
                if(isset($products[$goods['goods_id']])){
                    if($goods['sku_id'] > 0 && ($goods['sku_id'] != $sku_id || $goods['stock'] != $number)){
                        continue 2;
                    }elseif($goods['sku_id'] == 0 && $goods['stock'] != $number){
                        continue 2;
                    }
                }else{
                    continue 2;
                }
            }
            $rules = json_decode($activity['rules'],true);
            $package = [
                'id' => $activity['id'],
                'type' => $activity['type'],
                'title' => $activity['title'],
                'price' => $rules['price'],
            ];
        }
        return $package;
    }
}
